import store from "@/store/store";
import { navigate } from "@/util/navigate";
import { request, catchException } from "@/util/request";

async function bindReaderCard(data: Api.IBindCardProps) {
  try {
    const res = await request({
      loading: true,
      loadingText: "绑定中",
      method: "POST",
      url: "wechat/libInfo/bingReaderId",
      data,
    });
    uni.setStorageSync("account", data.account);
    const userToken = JSON.parse(uni.getStorageSync("userToken_zh_web") || "{}");
    userToken.account = data.account;
    uni.setStorageSync("userToken_zh_web", JSON.stringify(userToken));
    uni.showToast({ title: res.data.msg, icon: "none", duration: 2000 });
    setTimeout(() => navigate({ navMethod: "navigateBack" }), 2000);
  } catch (error) {
    uni.setStorageSync("account", "");
    catchException(error);
  }
}
async function getReaderCardInfo() {
  const { userState } = store;
  const userToken_zh_web = uni.getStorageSync('userToken_zh_web') || '{}'
  console.log(userToken_zh_web,'userToken_zh_web',typeof userToken_zh_web)
  if (userToken_zh_web=='{}') {
    return
  }
  try {
    const res = await request({
      loading: false,
      url: "wechat/userInfo/index",
      data: { token: true },
    });
    const data = res.data.content;
    userState.$patch({ ...data });
    uni.setStorageSync("account", data.account);
    uni.setStorageSync("readerCard", JSON.stringify(data));
    return data;
  } catch (error) {
    uni.setStorageSync("readerCard", "{}");
    uni.setStorageSync("account", "");
    // catchException(error);
    return {};
  }
}

function verifyReaderCardId(silence?: boolean) {
  const { userState } = store;
  let account = "";
  account = userState.account;
  if (!account) account = uni.getStorageSync("account");
  if (!account && !silence) {
    navigate({ url: "/pReaderCard/bindCard/index", navMethod: "redirect", auth: "required" });
  }
  return !!account;
}

export { bindReaderCard, getReaderCardInfo, verifyReaderCardId };
